<?php
/**
 * @copyright SilverBiology, LLC
 * @author Balachandran Viswanathan
 */
Class QueueOccurrence {
	public $db, $record;
	
	function __construct() {}

/**
* Loads the queue by id and load child fields
* @param int $queueId
* @param bool $flag : true - load the child fields
*/
	public function load_by_id($queueId) {
		$query = sprintf("SELECT * FROM `queue_occurrence` WHERE `queueId` = '%s';", mysql_escape_string($queueId) );
		$ret = $this->db->query_one( $query );
		if ($ret != NULL) {
			foreach( $ret as $field => $value ) {
				$this->record[$field] = $value;
			}
			return true;
		}
		return false;
	}

	public function save() {
		if($this->exists($this->get('queue_id'))) {
			$query = sprintf("UPDATE `queue_occurrence` SET  `occurrenceId` = '%s',  `imageId` = '%s', `dateAdded` = '%s' WHERE `queueId` = '%s' ;"
			, mysql_escape_string($this->get('occurrenceId'))
			, mysql_escape_string($this->get('imageId'))
			, mysql_escape_string($this->get('dateAdded'))
			, mysql_escape_string($this->get('queueId'))
			);
		} else {
			$query = sprintf("INSERT IGNORE INTO `queue_occurrence` SET  `occurrenceId` = '%s',  `imageId` = '%s', `dateAdded` = NOW();"
			, mysql_escape_string($this->get('occurrenceId'))
			, mysql_escape_string($this->get('imageId'))
			);
		}
		if($this->db->query($query)) {
			return true;
		} else {
			return false;
		}
	}
	

/**
* Returns a since field value
* @return mixed
*/
	public function get( $field ) {
		if (isset($this->record[$field])) {
			return( $this->record[$field] );
		} else {
			return( false );
		}
	}

/**
* Set the value to a field
* @return bool
*/
	public function set( $field, $value ) {
		$this->record[$field] = $value;
		return( true );
	}

	public function exists ($queueId){
		$query = sprintf("SELECT `queueId` FROM `queue_occurrence` WHERE `queueId` = '%s';", mysql_escape_string($queueId) );
		$ret = $this->db->query_one( $query );
		if ($ret == NULL) {
			return false;
		} else {
			return true;
		}
	}

	public function popQueue() {
		$query = "SELECT * FROM `queue_occurrence` ORDER BY `dateAdded` DESC LIMIT 1";
		$result = $this->db->query_one($query);
		if($result == NULL) {
			return false;
		} else {
			$delquery = sprintf("DELETE FROM `queue_occurrence` WHERE `queueId` = '%s' ", mysql_escape_string($result->queueId));
			if(!$this->db->query($delquery)) {
				return false;
			}
			return $result;
		}
	}
}



?>